package com.easy.activiti.listener;

import com.easy.activiti.ext.TaskEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.delegate.event.impl.ActivitiEntityWithVariablesEventImpl;
import org.activiti.engine.delegate.event.impl.ActivitiProcessStartedEventImpl;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;

/**
 * @author zhouchuang
 * 2024-11-05 15:03:46
 */
public abstract class AEventHandler implements EventHandler{
    public TaskEvent dispatchEvent(ActivitiEvent event) {
        String ProcessDefinitionId = event.getProcessDefinitionId();
        String processDefinitionKey = ProcessDefinitionId.split(":")[0];
        ActivitiEventType eventType = event.getType();
        String taskName = null;
        String businessKey = null;
        TaskEntity entity = null;
        String processInstanceId = event.getProcessInstanceId();
        if(event.getClass().isAssignableFrom(ActivitiEntityEventImpl.class)){
            ActivitiEntityEventImpl  eventImpl = (ActivitiEntityEventImpl) event;
            if(eventImpl.getEntity().getClass().isAssignableFrom(TaskEntityImpl.class)){
                entity = (TaskEntityImpl)eventImpl.getEntity();
                taskName = entity.getName();
                businessKey = entity.getProcessInstance().getBusinessKey();
            }else{
                ExecutionEntityImpl entity2 = (ExecutionEntityImpl)eventImpl.getEntity();
                taskName = entity2.getName();
                businessKey = entity2.getBusinessKey();
            }
        }else if(event.getClass().isAssignableFrom(ActivitiEntityWithVariablesEventImpl.class)){
            ActivitiEntityWithVariablesEventImpl eventImpl = (ActivitiEntityWithVariablesEventImpl) event;
            entity = (TaskEntityImpl)eventImpl.getEntity();
            taskName = entity.getName();
            businessKey = entity.getProcessInstance().getBusinessKey();
        }else{
            ActivitiProcessStartedEventImpl eventImpl = (ActivitiProcessStartedEventImpl) event;
            ExecutionEntityImpl entity2 = (ExecutionEntityImpl)eventImpl.getEntity();
            taskName = entity2.getName();
            businessKey = entity2.getParent().getBusinessKey();
        }
        System.out.println("processDefinitionKey="+processDefinitionKey);
        System.out.println("businessKey="+businessKey);
        TaskEvent  taskEvent = new TaskEvent(processDefinitionKey,processInstanceId,businessKey,entity);
        //执行指定方法
        getActuator(processDefinitionKey+taskName+eventType.name()).execute(taskEvent);
        //执行基本方法拒绝
        return taskEvent;
    }
}
